package com.jixiang.goods.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jixiang.goods.dao.GsGoodsTypeDao;
import com.jixiang.goods.service.GsGoodsInfoService;
import com.jixiang.goods.service.GsTypePicService;
import com.jixiang.model.common.dtos.ResponseResult;
import com.jixiang.model.common.enums.AppHttpCodeEnum;
import com.jixiang.model.dictionary.entity.DsLayoutMenu;
import com.jixiang.model.goods.dtos.AddGoodsTypePicDtos;
import com.jixiang.model.goods.dtos.AddGoodsTypeWxPicDtos;
import com.jixiang.model.goods.dtos.GoodsBySecTypeDtos;
import com.jixiang.model.goods.dtos.GsGoodsWxAllDtos;
import com.jixiang.model.goods.entity.GsGoodsInfo;
import com.jixiang.model.goods.entity.GsGoodsType;
import com.jixiang.goods.service.GsGoodsTypeService;
import com.jixiang.model.goods.entity.GsPic;
import com.jixiang.model.goods.entity.GsTypePic;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.jixiang.common.constants.GoodsIndexConstants.MAPPING_NAME;
import static com.jixiang.common.constants.RedisConstants.*;

/**
 * (GsGoodsType)表服务实现类
 *
 * @author makejava
 * @since 2023-10-14 21:13:16
 */
@Service("gsGoodsTypeService")
public class GsGoodsTypeServiceImpl extends ServiceImpl<GsGoodsTypeDao, GsGoodsType> implements GsGoodsTypeService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Resource
    private GsGoodsInfoService gsGoodsInfoService;
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Resource
    private GsTypePicService gsTypePicService;
    @Resource
    RedissonClient redissonClient;
    @Override
    public ResponseResult getGoodsTypePage(int pageNum,int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<GsGoodsType> goodsTypeList = query().eq("level",1).orderByAsc("priority").list();
        goodsTypeList.forEach(item1 -> {
            List<GsGoodsType> list1 = query().orderByAsc("priority").eq("parent_goods_type_id",item1.getId()).list();
            if(!list1.isEmpty() || list1 != null){
                item1.setChildren(list1);
                list1.forEach(item2 -> {
                    List<GsGoodsType> list2 = query().orderByAsc("priority").eq("parent_goods_type_id",item2.getId()).list();
                    if(!list2.isEmpty() || list2 != null){
                        item2.setChildren(list2);
                    }
                });
            }
        });
        PageInfo page = new PageInfo(goodsTypeList);
        return ResponseResult.okResult(page);
    }

    @Override
    public ResponseResult getParentGoodsTypeList() {
        List<GsGoodsType> goodsTypeList = query().eq("level",1).orderByAsc("priority").list();
        goodsTypeList.forEach(item1 -> {
            List<GsGoodsType> list1 = query().orderByAsc("priority").eq("parent_goods_type_id",item1.getId()).list();
            if(!list1.isEmpty() || list1 != null){
                item1.setChildren(list1);
            }
        });
        return ResponseResult.okResult(goodsTypeList);
    }

    @Override
    public ResponseResult addGoodsType(GsGoodsType gsGoodsType) {
        stringRedisTemplate.delete(REDIS_PREX_GSGOODSTYPE);
//        delRedisGoodsTypeDataById(gsGoodsType.getId());
        boolean save = save(gsGoodsType);

        stringRedisTemplate.delete(REDIS_PREX_GSGOODSTYPE);
        delRedisGoodsTypeDataById(gsGoodsType.getId());
        return ResponseResult.okResult("添加成功");
    }
    void delRedisGoodsTypeDataById( Long id){
        GsGoodsType gsGoodsType = query().eq("id", id).list().get(0);
        if(gsGoodsType.getLevel() == 1){
            Boolean delete = stringRedisTemplate.delete(REDIS_PREX_GSGOODSTYPEBYID + id.toString());
            List<GsGoodsType> goodsTypeList = query().eq("parent_goods_type_id", gsGoodsType.getId()).list();
            if(goodsTypeList!= null &&(!goodsTypeList.isEmpty())){
                goodsTypeList.forEach(item -> {
                    stringRedisTemplate.delete(REDIS_PREX_SECONDGSGOODSTYPEPICBYID + item.getId());
                });
            }

        }else if(gsGoodsType.getLevel() == 2){
            Boolean delete = stringRedisTemplate.delete(REDIS_PREX_GSGOODSTYPEBYID + gsGoodsType.getParentGoodsTypeId().toString());
            Boolean delete2 = stringRedisTemplate.delete(REDIS_PREX_SECONDGSGOODSTYPEPICBYID + id);
        }else if(gsGoodsType.getLevel() == 3){
            GsGoodsType gsGoodsType1 = query().eq("id", gsGoodsType.getParentGoodsTypeId()).list().get(0);
//            GsGoodsType gsGoodsType2 = query().eq("id", gsGoodsType1.getParentGoodsTypeId()).list().get(0);
            Boolean delete = stringRedisTemplate.delete(REDIS_PREX_GSGOODSTYPEBYID + gsGoodsType1.getParentGoodsTypeId().toString());
            List<GsGoodsType> goodsTypeList = query().eq("id", gsGoodsType.getParentGoodsTypeId()).list();
            if(goodsTypeList!=null && (!goodsTypeList.isEmpty())){
                goodsTypeList.forEach(item -> {
                    stringRedisTemplate.delete(REDIS_PREX_SECONDGSGOODSTYPEPICBYID + item.getId());
                });
            }
        }


    }

    void delRedisGoodsTypeDataByIdAll( Long id,Long parendId,int level){
//        GsGoodsType gsGoodsType = query().eq("id", id).list().get(0);
        if(level == 1){
            Boolean delete = stringRedisTemplate.delete(REDIS_PREX_GSGOODSTYPEBYID + id.toString());
            List<GsGoodsType> goodsTypeList = query().eq("parent_goods_type_id", id).list();
            if(goodsTypeList!= null &&(!goodsTypeList.isEmpty())){
                goodsTypeList.forEach(item -> {
                    stringRedisTemplate.delete(REDIS_PREX_SECONDGSGOODSTYPEPICBYID + item.getId());
                });
            }

        }else if(level == 2){
            Boolean delete = stringRedisTemplate.delete(REDIS_PREX_GSGOODSTYPEBYID + parendId.toString());
            Boolean delete2 = stringRedisTemplate.delete(REDIS_PREX_SECONDGSGOODSTYPEPICBYID + id);
        }else if(level == 3){
            GsGoodsType gsGoodsType1 = query().eq("id", parendId).list().get(0);
//            GsGoodsType gsGoodsType2 = query().eq("id", gsGoodsType1.getParentGoodsTypeId()).list().get(0);
            Boolean delete = stringRedisTemplate.delete(REDIS_PREX_GSGOODSTYPEBYID + gsGoodsType1.getParentGoodsTypeId().toString());
            List<GsGoodsType> goodsTypeList = query().eq("id", gsGoodsType1.getParentGoodsTypeId()).list();
            if(goodsTypeList!=null && (!goodsTypeList.isEmpty())){
                goodsTypeList.forEach(item -> {
                    stringRedisTemplate.delete(REDIS_PREX_SECONDGSGOODSTYPEPICBYID + item.getId());
                });
            }
        }


    }
    @Override
    public ResponseResult getGoodsTypeById(String id) {
        GsGoodsType gsGoodsType = getById(id);
        return ResponseResult.okResult(gsGoodsType);
    }

    @Override
    public ResponseResult updateGoodsType(GsGoodsType gsGoodsType) {
        stringRedisTemplate.delete(REDIS_PREX_GSGOODSTYPE);
        delRedisGoodsTypeDataById(gsGoodsType.getId());
        boolean b = updateById(gsGoodsType);
        stringRedisTemplate.delete(REDIS_PREX_GSGOODSTYPE);
        delRedisGoodsTypeDataById(gsGoodsType.getId());
        return ResponseResult.okResult("修改成功");
    }

//    @Override
//    public ResponseResult deleteGoodsTypeById(String id) {
//        stringRedisTemplate.delete(REDIS_PREX_GSGOODSTYPE);
//        List<GsGoodsType> goodsTypeList = query().eq("parent_goods_type_id", id).list();
//        if(goodsTypeList.isEmpty() || goodsTypeList==null){
//            boolean b = removeById(id);
//            return ResponseResult.okResult("删除成功");
//        }
//        stringRedisTemplate.delete(REDIS_PREX_GSGOODSTYPE);
//        return ResponseResult.errorResult(AppHttpCodeEnum.MSQL_DELETE_ERROR);
//    }

    @Override
    public ResponseResult deleteGoodsTypeById(String id) {
        delRedisGoodsTypeDataById(Long.valueOf(id));
        List<GsGoodsType> goodsTypeList = query().eq("parent_goods_type_id", id).list();
        if(!goodsTypeList.isEmpty() ){
            return ResponseResult.errorResult(AppHttpCodeEnum.MSQL_DELETE_ERROR);
        }
        List<GsGoodsInfo> list = gsGoodsInfoService.query().eq("goods_type_id", id).list();
        if(!list.isEmpty()){
            return ResponseResult.errorResult(AppHttpCodeEnum.MSQL_DELETE_ERROR);
        }
        stringRedisTemplate.delete(REDIS_PREX_GSGOODSTYPE);
        GsGoodsType gsGoodsType = query().eq("id", id).list().get(0);
        Integer level = gsGoodsType.getLevel();
        Long parentGoodsTypeId = gsGoodsType.getParentGoodsTypeId();
        boolean b = removeById(id);
        delRedisGoodsTypeDataByIdAll(Long.valueOf(id),parentGoodsTypeId,level);
        stringRedisTemplate.delete(REDIS_PREX_GSGOODSTYPE);
        return ResponseResult.okResult("删除成功");
    }


//    @Override
//    public ResponseResult appGetGoodsTypeList(Integer level) {
//        if(level == 0 || level==null){
//            level =1;
//        }
//        List<GsGoodsType> goodsTypeList = query().eq("level",1).orderByAsc("priority").list();
//        if(level == 1){
//            return ResponseResult.okResult(goodsTypeList);
//        }
//        goodsTypeList.forEach(item1 -> {
//            List<GsGoodsType> list1 = query().orderByAsc("priority").eq("parent_goods_type_id",item1.getId()).list();
//            if(!list1.isEmpty() || list1 != null){
//                item1.setChildren(list1);
//            }
//        });
//        if(level == 2){
//            return ResponseResult.okResult(goodsTypeList);
//        }
//        goodsTypeList.forEach(item1 -> {
//            List<GsGoodsType> list1 = query().orderByAsc("priority").eq("parent_goods_type_id",item1.getId()).list();
//            if(!list1.isEmpty() || list1 != null){
//                item1.setChildren(list1);
//                list1.forEach(item2 -> {
//                    List<GsGoodsType> list2 = query().orderByAsc("priority").eq("parent_goods_type_id",item2.getId()).list();
//                    if(!list2.isEmpty() || list2 != null){
//                        item2.setChildren(list2);
//                    }
//                });
//            }
//        });
//        return ResponseResult.okResult(goodsTypeList);
//    }

    @Override
    public ResponseResult appGetGoodsTypeList() {
        String jsonObj = stringRedisTemplate.opsForValue().get(REDIS_PREX_GSGOODSTYPE);
        if(StrUtil.isNotBlank(jsonObj)){
            List<GsGoodsType> list = JSONUtil.toList(jsonObj, GsGoodsType.class);
            return ResponseResult.okResult(list);
        }
        List<GsGoodsType> goodsTypeList = query().eq("level",1).orderByAsc("priority").list();
        goodsTypeList.forEach(item1 -> {
            List<GsGoodsType> list1 = query().orderByAsc("priority").eq("parent_goods_type_id",item1.getId()).list();
            if(!list1.isEmpty() || list1 != null){
                item1.setChildren(list1);
                list1.forEach(item2 -> {
                    List<GsGoodsType> list2 = query().orderByAsc("priority").eq("parent_goods_type_id",item2.getId()).list();
                    if(!list2.isEmpty() || list2 != null){
                        item2.setChildren(list2);
                    }
                });
            }
        });
        JSONArray objects = JSONUtil.parseArray(goodsTypeList);
        stringRedisTemplate.opsForValue().set(REDIS_PREX_GSGOODSTYPE,objects.toString());
        return ResponseResult.okResult(goodsTypeList);
    }

    @Override
    public ResponseResult clearGoodsTypeCache() {
        stringRedisTemplate.delete(REDIS_PREX_GSGOODSTYPE);
        List<GsGoodsType> goodsTypeList = query().eq("level", 1).list();
        goodsTypeList.forEach(item -> {
            delRedisGoodsTypeDataById(item.getId());
        });
        return ResponseResult.okResult("缓存清理成功");
    }

    @Override
    public ResponseResult getGoodsTypeList() {
        List<GsGoodsType> goodsTypeList = query().eq("level",1).orderByAsc("priority").list();
        goodsTypeList.forEach(item1 -> {
            List<GsGoodsType> list1 = query().orderByAsc("priority").eq("parent_goods_type_id",item1.getId()).list();
            if(!list1.isEmpty() || list1 != null){
                item1.setChildren(list1);
                list1.forEach(item2 -> {
                    List<GsGoodsType> list2 = query().orderByAsc("priority").eq("parent_goods_type_id",item2.getId()).list();
                    if(!list2.isEmpty() || list2 != null){
                        item2.setChildren(list2);
                    }
                });
            }
        });
        return ResponseResult.okResult(goodsTypeList);
    }

    @Override
    public ResponseResult appGetGoodsTypeLayout() {
        String jsonObj = stringRedisTemplate.opsForValue().get(REDIS_PREX_GSGOODSTYPE);
        List<GsGoodsType> list = new ArrayList<>();
        if(StrUtil.isNotBlank(jsonObj)){
            list = JSONUtil.toList(jsonObj, GsGoodsType.class);
//            return ResponseResult.okResult(list);
        }else {
            List<GsGoodsType> goodsTypeList = query().eq("level",1).orderByAsc("priority").list();
            goodsTypeList.forEach(item1 -> {
                List<GsGoodsType> list1 = query().orderByAsc("priority").eq("parent_goods_type_id",item1.getId()).list();
                if(!list1.isEmpty() || list1 != null){
                    item1.setChildren(list1);
                    list1.forEach(item2 -> {
                        List<GsGoodsType> list2 = query().orderByAsc("priority").eq("parent_goods_type_id",item2.getId()).list();
                        if(!list2.isEmpty() || list2 != null){
                            item2.setChildren(list2);
                        }
                    });
                }
            });
            JSONArray objects = JSONUtil.parseArray(goodsTypeList);
            stringRedisTemplate.opsForValue().set(REDIS_PREX_GSGOODSTYPE,objects.toString());
            list = goodsTypeList;
        }
        if(list == null || (list.isEmpty())){
            return ResponseResult.okResult(list);
        }
        list.forEach(item -> {
            List<GsGoodsInfo> goodsList = new ArrayList<>();
            List<GsGoodsType> children = item.getChildren();
            if(children != null && (!children.isEmpty())){
                children.forEach(items -> {
                    List<GsGoodsType> childrens = items.getChildren();
                    if (childrens != null && (!childrens.isEmpty())) {
                        childrens.forEach(itemss -> {
                            try {
                                SearchRequest searchRequest = new SearchRequest(MAPPING_NAME);
                                BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                                boolQueryBuilder.must(QueryBuilders.termQuery("goodsState",1)).must(QueryBuilders.termQuery("goodsTypeId",itemss.getId()));
                                searchRequest.source().query(boolQueryBuilder).sort("createTime", SortOrder.DESC);
                                SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
                                SearchHits searchHits = response.getHits();
                                SearchHit[] hits = searchHits.getHits();
//                    for (SearchHit hit : hits) {
//                        String json = hit.getSourceAsString();
//                        GsGoodsInfo gsGoodsInfo = JSON.parseObject(json, GsGoodsInfo.class);
//                        goodsList.add(gsGoodsInfo);
//                    }
                                for(int i=0;i<hits.length;i++){
                                    if(i == 10){
                                        break;
                                    }
                                    String json = hits[i].getSourceAsString();
                                    GsGoodsInfo gsGoodsInfo = JSON.parseObject(json, GsGoodsInfo.class);
                                    goodsList.add(gsGoodsInfo);
                                }
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        });
                    }
                });
            }
            item.setGoodsInfo(goodsList);
        });


        return ResponseResult.okResult(list);
    }

    @Override
    public ResponseResult addPic(AddGoodsTypePicDtos addGoodsTypePicDtos) {
        stringRedisTemplate.delete(REDIS_PREX_GSGOODSTYPEPICBYID+addGoodsTypePicDtos.getTypeId());
        LambdaQueryWrapper<GsTypePic> gsGoodsTypeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        gsGoodsTypeLambdaQueryWrapper.eq(GsTypePic::getGoodsTypeId,addGoodsTypePicDtos.getTypeId());
        boolean remove = gsTypePicService.remove(gsGoodsTypeLambdaQueryWrapper);
        addGoodsTypePicDtos.getTypeList().forEach(item -> {
            GsTypePic gsTypePic = new GsTypePic();
            gsTypePic.setPic(item.getUrl());
            gsTypePic.setGoodsTypeId(Long.valueOf(addGoodsTypePicDtos.getTypeId()));
            gsTypePicService.save(gsTypePic);
        });

        stringRedisTemplate.delete(REDIS_PREX_GSGOODSTYPEPICBYID+addGoodsTypePicDtos.getTypeId());
        return ResponseResult.okResult("保存成功");
    }

    @Override
    public ResponseResult appGetGoodsTypeDataById(String id) {
        String redisObj = stringRedisTemplate.opsForValue().get(REDIS_PREX_GSGOODSTYPEBYID + id);
        if(StrUtil.isNotBlank(redisObj)){
            GsGoodsType bean = JSONUtil.toBean(redisObj, GsGoodsType.class);
            return ResponseResult.okResult(bean);
        }
        if(redisObj!=null){
//            return ResponseResult.errorResult(500,"空参数");
            return ResponseResult.okResult(null);
        }
        RLock lock = redissonClient.getLock(REDIS_LOCK_GSGOODSTYPEBYID + id);

        GsGoodsType gsGoodsType = null;
        try {
            boolean isLock = lock.tryLock(300, TimeUnit.MILLISECONDS);
            if(!isLock){
                    appGetGoodsTypeDataById(id);
            }
            gsGoodsType = query().eq("id", id).list().get(0);
            if(gsGoodsType == null){
                stringRedisTemplate.opsForValue().set(REDIS_PREX_GSGOODSTYPEBYID+id,"");
            }else {
                List<GsGoodsType> goodsTypeList = query().eq("parent_goods_type_id", id).list();
                if(goodsTypeList!= null && !goodsTypeList.isEmpty()){
                    goodsTypeList.forEach(item -> {
                        List<GsGoodsInfo> goodsList =new ArrayList<>();
                        List<GsGoodsType> goodsTypeListLevel3 = query().eq("parent_goods_type_id", item.getId()).list();
                        if(goodsTypeListLevel3 != null && (!goodsTypeListLevel3.isEmpty())){
                            goodsTypeListLevel3.forEach(items -> {
                                List<GsGoodsInfo> list = gsGoodsInfoService.query().eq("goods_type_id", items.getId()).list();
                                if(list!=null && (!list.isEmpty())){
                                    goodsList.addAll(list);
                                }
                            });
                        }
                        item.setGoodsInfo(goodsList);
                    });
                }
                gsGoodsType.setChildren(goodsTypeList);
                String jsonStr = JSONUtil.toJsonStr(gsGoodsType);
                stringRedisTemplate.opsForValue().set(REDIS_PREX_GSGOODSTYPEBYID+id,jsonStr);
            }

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }
        return ResponseResult.okResult(gsGoodsType);
    }

    @Override
    public ResponseResult appGetGoodsTypePicDataById(String id) {
        String redisData = stringRedisTemplate.opsForValue().get(REDIS_PREX_GSGOODSTYPEPICBYID + id);
        if(StrUtil.isNotBlank(redisData)){
            List<GsTypePic> list = JSONUtil.toList(redisData, GsTypePic.class);
            return  ResponseResult.okResult(list);
        }
        if(redisData!=null){
//            return ResponseResult.errorResult(500,"无此数据");
            return ResponseResult.okResult(null);
        }
        RLock lock = redissonClient.getLock(REDIS_LOCK_GSGOODSTYPEPICBYID + id);
        List<GsTypePic> list = new ArrayList<>();
        try {
            boolean b = lock.tryLock(500, TimeUnit.MILLISECONDS);
            if(!b){
                appGetGoodsTypePicDataById(id);
            }

            list = gsTypePicService.query().eq("goods_type_id", id).list();
            if(list !=null && (!list.isEmpty())){
                JSONArray objects = JSONUtil.parseArray(list);
                stringRedisTemplate.opsForValue().set(REDIS_PREX_GSGOODSTYPEPICBYID+id,objects.toString());
            }else {
                stringRedisTemplate.opsForValue().set(REDIS_PREX_GSGOODSTYPEPICBYID+id,"");
            }

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
        return ResponseResult.okResult(list);
    }

    @Override
    public ResponseResult appGetSecondGoodsTypeDataById(String id) {
//        String redisData = stringRedisTemplate.opsForValue().get(REDIS_PREX_SECONDGSGOODSTYPEPICBYID + id);
//        if(StrUtil.isNotBlank(redisData)){
//            GsGoodsType bean = JSONUtil.toBean(redisData, GsGoodsType.class);
//            return ResponseResult.okResult(bean);
//        }
//        if(redisData!=null){
//            return ResponseResult.okResult(null);
//        }
//        RLock lock = redissonClient.getLock(REDIS_LOCK_SECONDGSGOODSTYPEPICBYID);
//        GsGoodsType gsGoodsType = new GsGoodsType();
//        try {
//            boolean b = lock.tryLock(500, TimeUnit.SECONDS);
//            if(!b){
//                Thread.sleep(1000);
//                appGetSecondGoodsTypeDataById(id);
//            }
//             gsGoodsType = query().eq("id", id).list().get(0);
//
//            GsGoodsType gsParentGoodsType = query().eq("id", gsGoodsType.getId()).list().get(0);
//            gsGoodsType.setParentGoodsTypeName(gsParentGoodsType.getName());
//
//            List<GsGoodsType> goodsTypeList = query().eq("parent_goods_type_id", id).list();
//            gsGoodsType.setChildren(goodsTypeList);
//            JSONObject jsonObject = JSONUtil.parseObj(gsGoodsType);
//            stringRedisTemplate.opsForValue().set(REDIS_PREX_SECONDGSGOODSTYPEPICBYID+id,jsonObject.toString());
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        } finally {
//            lock.unlock();
//        }
        GsGoodsType secondGoodsTypeDataById = getSecondGoodsTypeDataById(id);
        return ResponseResult.okResult(secondGoodsTypeDataById);
    }

    @Override
    public ResponseResult appGetGoodsInfoBySecondGoodsTypeId(GoodsBySecTypeDtos goodsBySecTypeDtos) {
        SearchRequest searchRequest = new SearchRequest(MAPPING_NAME);

        GsGoodsType goodsType = getSecondGoodsTypeDataById(goodsBySecTypeDtos.getPageGoodsTypeId());
        List<GsGoodsType> children = goodsType.getChildren();
        if(children == null ||children.isEmpty()){
            return  ResponseResult.okResult(null);
        }
//        LinkedList<Long> stringsList = new LinkedList<>();
//        children.forEach(item -> {
////            boolQueryBuilder.must(QueryBuilders.termQuery("goodsTypeId",item.getId()));
//            stringsList.add(item.getId());
//        });
//        boolQueryBuilder.must(QueryBuilders.termQuery("goodsTypeId","1714189057879224322"));
//        boolQueryBuilder.must(QueryBuilders.termQuery("goodsTypeId","1719921198239854593"));
//        boolQueryBuilder.must(QueryBuilders.termQuery("goodsTypeId","1714189057879224322"));

//        boolQueryBuilder.must(QueryBuilders.termsQuery("goodsTypeId","1719921198239854593","1714189057879224322"));
//        boolQueryBuilder.must(QueryBuilders.termsQuery("goodsTypeId","1719921198239854593","1714189057879224322"));
//        boolQueryBuilder.must(QueryBuilders.termQuery("goodsState",1));
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termQuery("parentGoodsTypeId",goodsType.getId())).must(QueryBuilders.termQuery("goodsState",1));
        searchRequest.source().query(boolQueryBuilder).sort(goodsBySecTypeDtos.getPageSort(), SortOrder.DESC).from((goodsBySecTypeDtos.getPageNum()-1)*goodsBySecTypeDtos.getPageSize()).size(goodsBySecTypeDtos.getPageSize());
        List<GsGoodsInfo> list = new ArrayList<GsGoodsInfo>();
        try {
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            list = handleGoodsResponse(search);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseResult.okResult(list);
    }

    @Override
    public ResponseResult getGoodsTypeWxPic(String id) {
        GsGoodsType gsGoodsType = query().eq("id", id).list().get(0);

        return ResponseResult.okResult(gsGoodsType.getWxPic());
    }

    @Override
    public ResponseResult dddGoodsTypeWxPic(AddGoodsTypeWxPicDtos addGoodsTypeWxPicDtos) {
        GsGoodsType gsGoodsType = query().eq("id", addGoodsTypeWxPicDtos.getTypeId()).list().get(0);
        if(gsGoodsType == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        gsGoodsType.setWxPic(addGoodsTypeWxPicDtos.getImageUrl());
        boolean b = updateById(gsGoodsType);
        return ResponseResult.okResult("修改成功");
    }

    @Override
    public ResponseResult WxGetGoodsListByRecommend(int pageNum, int pageSize) {
        SearchRequest searchRequest = new SearchRequest(MAPPING_NAME);
        searchRequest.source().sort("createTime", SortOrder.DESC).from((pageNum - 1) * pageSize).size(pageSize);
        List<GsGoodsInfo> list = new ArrayList<GsGoodsInfo>();
        int total = 0;
        try {
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            total = (int)search.getHits().getTotalHits().value;
            list = handleGoodsResponse(search);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        GsGoodsWxAllDtos gsGoodsWxAllDtos = new GsGoodsWxAllDtos();
        gsGoodsWxAllDtos.setGoodsList(list);
        gsGoodsWxAllDtos.setTotal(total);
        gsGoodsWxAllDtos.setPageNum(pageNum);
        gsGoodsWxAllDtos.setPageSize(pageSize);
        int ceil = (int) Math.ceil(total / pageSize);
        gsGoodsWxAllDtos.setPageSum(ceil);
        return ResponseResult.okResult(gsGoodsWxAllDtos);
    }
//    List<GsGoodsInfo> getByTypeId(long id){
//        SearchRequest searchRequest = new SearchRequest(MAPPING_NAME);
//        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//        boolQueryBuilder.must(QueryBuilders.termQuery("goodsTypeId",id)).must(QueryBuilders.termQuery("goodsState",1));
//        searchRequest.source().query(boolQueryBuilder).sort(goodsBySecTypeDtos.getPageSort(), SortOrder.DESC).from((goodsBySecTypeDtos.getPageNum()-1)*goodsBySecTypeDtos.getPageSize()).size(goodsBySecTypeDtos.getPageSize());
//        List<GsGoodsInfo> list = new ArrayList<GsGoodsInfo>();
//        try {
//            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//            list = handleGoodsResponse(search);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        return List;
//    }

    List<GsGoodsInfo> handleGoodsResponse(SearchResponse search){
        LinkedList<GsGoodsInfo> list = new LinkedList<>();
        SearchHits searchHits = search.getHits();
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            GsGoodsInfo gsGoodsInfo = JSON.parseObject(json, GsGoodsInfo.class);
            list.add(gsGoodsInfo);
        }
        return list;
    }


    public GsGoodsType getSecondGoodsTypeDataById(String id){
        String redisData = stringRedisTemplate.opsForValue().get(REDIS_PREX_SECONDGSGOODSTYPEPICBYID + id);
        if(StrUtil.isNotBlank(redisData)){
            GsGoodsType bean = JSONUtil.toBean(redisData, GsGoodsType.class);
            return bean;
        }
        if(redisData!=null){
            return  null;
        }
        RLock lock = redissonClient.getLock(REDIS_LOCK_SECONDGSGOODSTYPEPICBYID);
        GsGoodsType gsGoodsType = new GsGoodsType();
        try {
            boolean b = lock.tryLock(500, TimeUnit.SECONDS);
            if(!b){
                Thread.sleep(1000);
                appGetSecondGoodsTypeDataById(id);
            }
            gsGoodsType = query().eq("id", id).list().get(0);

            GsGoodsType gsParentGoodsType = query().eq("id", gsGoodsType.getParentGoodsTypeId()).list().get(0);
            gsGoodsType.setParentGoodsTypeName(gsParentGoodsType.getName());

            List<GsGoodsType> goodsTypeList = query().eq("parent_goods_type_id", id).list();
            if(goodsTypeList!= null &&(!goodsTypeList.isEmpty())){
                gsGoodsType.setChildren(goodsTypeList);
            }
            JSONObject jsonObject = JSONUtil.parseObj(gsGoodsType);
            stringRedisTemplate.opsForValue().set(REDIS_PREX_SECONDGSGOODSTYPEPICBYID+id,jsonObject.toString());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
        return gsGoodsType;
    }

}

